package com.blue.scheduled.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.blue.po.system.ErrorLogsPO;
import com.blue.po.system.OperationLogsPO;
import com.blue.scheduled.logs.annotation.JobLog;
import com.blue.service.system.IErrorLogsService;
import com.blue.service.system.IOperationLogsService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

@Slf4j
public class ClearLogsTask extends QuartzJobBean {

    @Resource
    private IErrorLogsService errorLogsService;

    @Resource
    private IOperationLogsService operationLogsService;


    @Override
    @JobLog
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        log.info("开始执行清理系统日志批处理-----------------------------");
        JobDataMap dataMap = context.getMergedJobDataMap();
        String day = (String) dataMap.get("params");
        if (StringUtils.isBlank(day)) {
            day = "5";
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.DATE, Integer.parseInt(day));
        Date date = calendar.getTime();
        String before = new SimpleDateFormat("yyyy-MM-dd").format(date);
        log.info("清理的数据日期为{}之前的数据", before);
        log.info("开始执行清理系统错误日志");
        errorLogsService.remove(new LambdaQueryWrapper<ErrorLogsPO>()
                .le(ErrorLogsPO::getDate, before));
        log.info("系统错误日志清理成功");
        log.info("开始执行清理系统操作日志");
        operationLogsService.remove(new LambdaQueryWrapper<OperationLogsPO>()
                .le(OperationLogsPO::getDate, before));
        log.info("系统操作日志清理成功");
        log.info("清理系统日志批处理已完成-----------------------------");
    }
}
